package cn.tedu.ivos.service.impl;

import cn.tedu.ivos.base.constant.UserStatus;
import cn.tedu.ivos.base.utils.StringUtils;
import cn.tedu.icop.api.domain.SysUser;
import cn.tedu.ivos.pojo.vo.LoginUser;
import cn.tedu.ivos.repository.UserMapper;
import cn.tedu.ivos.service.template.PasswordTemplate;
import cn.tedu.ivos.base.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordTemplate passwordService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser sysUser = userMapper.selectByUsername(username);
        System.out.println(sysUser);
        if (StringUtils.isNull(sysUser))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("user.not.exists");
        }
        else if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("user.password.delete");
        }
        else if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("user.blocked");
        }

        passwordService.validate(sysUser.getPassword());

        return createLoginUser(sysUser);
    }

  public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user,userMapper.selectUserPermissions(user.getId()));
    }
}
